<template>
  <el-form :inline="true" :model="Grt" class="demo-form-inline">
    <el-form-item label="订单单号">
      <el-input v-model="Grt.AssociatedOrderNumber" placeholder="请输入订单单号" clearable/>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="GetStockingLsit()">查询</el-button>
    </el-form-item>
  </el-form>

  <!-- 测试按钮 -->
  <div style="margin: 10px 0;">
    <el-button @click="testPagination">测试分页功能</el-button>
    <el-button @click="forceRefresh">强制刷新</el-button>
    <el-button @click="testSmallPageSize">测试小页面大小</el-button>
  </div>

  <el-table :data="tableData" style="width: 100%">
    <el-table-column prop="associatedOrderNumber" label="订单号" width="90" />
    <el-table-column prop="supplierName" label="供应商名称" width="90" />
    <el-table-column prop="productName" label="产品名称" width="90" />
    <el-table-column prop="supplierContact" label="供应商联系人" width="90" />
    <el-table-column prop="price" label="单价" width="80"  />
    <el-table-column prop="supplierPhone" label="供应商联系方式" width="80" />
    <el-table-column prop="manufacturerCode" label="产品编号" width="80" />
    <el-table-column prop="supplierCode" label="供应商编号" width="80" />
    <el-table-column prop="preparedName" label="制单人" width="80" />
    <el-table-column prop="preparedTime" label="制单时间" width="80">
      <template #default="scope">
        <!-- 时间格式年月日 -->
        {{ scope.row.preparedTime ? scope.row.preparedTime.slice(0, 10) : '' }}
      </template>
    </el-table-column>
    <el-table-column prop="stateName" label="审批人" width="80" />
    <el-table-column prop="depotName" label="库位" width="80" />
    <el-table-column prop="supplierContact" label="供应商联系人" width="80" />
    <el-table-column prop="state" label="状态" width="80">
      <template #default="scope">
        <!-- 三目运算符 -->
        {{ scope.row.state === 0 ? '待审批' : scope.row.state === 1 ? '已审批' : '已入库' }}
      </template>
    </el-table-column>
    <el-table-column prop="stateRc" label="类型" width="80">
      <template #default="scope">
        {{ scope.row.stateRc === 1 ? '入库' : scope.row.stateRc === 0 ? '出库' : '未知' }}
      </template>
    </el-table-column>
    <el-table-column label="操作">
      <template #default="scope">
        <el-button type="text" @click="Dletee(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <!-- 分页组件 -->
  <el-pagination v-if="page.totaCount > 0" :current-page="page.PageIndex" :page-size="page.PageSize"
    :page-sizes="[5, 10, 20, 30]" layout="total, sizes, prev, pager, next, jumper" :total="page.totaCount"
    @size-change="handleSizeChange" @current-change="handleCurrentChange" next-text="下一页" prev-text="上一页"
    @click="testPaginationClick">
  </el-pagination>
</template>

<script lang="ts" setup>
import axios from 'axios';
import { ElMessageBox } from 'element-plus';
import { ElMessage } from 'element-plus';
import { onMounted, ref } from 'vue';
import http from '@/http/axiosHelper';
const tableData:any = ref([]);
const page = ref({
  PageIndex: 1,
  PageSize: 10,
  pageCount: 0,
  totaCount: 0,
})
const Grt = ref({
  State: '',
  AssociatedOrderNumber: "",
})

onMounted(() => {
  GetStockingLsit();
})

// 测试分页功能
const testPagination = () => {
  alert('测试分页功能按钮被点击了！');
  console.log('=== 测试分页功能 ===');
  console.log('当前分页状态:', page.value);
  console.log('表格数据长度:', tableData.value.length);

  // 模拟翻页
  page.value.PageIndex = 2;
  console.log('模拟翻到第2页');
  console.log('翻页后的状态:', page.value);
  GetStockingLsit();
}

// 强制刷新
const forceRefresh = () => {
  alert('强制刷新按钮被点击了！');
  console.log('=== 强制刷新被触发 ===');
  console.log('刷新前的状态:', page.value);

  page.value.PageIndex = 1;
  page.value.PageSize = 10;

  console.log('刷新后的状态:', page.value);
  console.log('开始调用 GetStockingLsit...');
  GetStockingLsit();
}

// 测试小页面大小
const testSmallPageSize = () => {
  alert('测试小页面大小按钮被点击了！');
  console.log('=== 测试小页面大小 ===');
  console.log('设置前状态:', page.value);

  page.value.PageSize = 1; // 每页只显示1条
  page.value.PageIndex = 1;

  console.log('设置后状态:', page.value);
  console.log('现在应该有3页了');
  GetStockingLsit();
}

const GetStockingLsit = () => {
  // 确保参数类型正确
  const params: any = {
    PageIndex: parseInt(page.value.PageIndex.toString()),
    PageSize: parseInt(page.value.PageSize.toString()),
  };

  // 可选参数
  if (Grt.value.State && Grt.value.State !== '') {
    params.State = parseInt(Grt.value.State.toString());
  }
  if (Grt.value.AssociatedOrderNumber && Grt.value.AssociatedOrderNumber !== '') {
    params.AssociatedOrderNumber = Grt.value.AssociatedOrderNumber;
  }

  console.log('=== 请求开始 ===');
  console.log('请求参数:', params);
  console.log('当前分页状态:', {
    PageIndex: page.value.PageIndex,
    PageSize: page.value.PageSize,
    totaCount: page.value.totaCount
  });

  http.get("/shangyou/api/Stocking/GetStocking", { params })
    .then(res => {
      console.log('=== 接口响应 ===');
      console.log('完整响应:', res);
      console.log('响应数据:', res.data);

      // 检查响应结构
      if (res.data) {
        // 处理分页数据
        if (Array.isArray(res.data.pageData)) {
          tableData.value = res.data.pageData;
          console.log('数据条数:', tableData.value.length);
        } else if (Array.isArray(res.data)) {
          tableData.value = res.data;
          console.log('数据条数:', tableData.value.length);
        } else {
          tableData.value = [];
          console.warn('响应数据格式不正确，没有找到数据数组');
        }

        // 处理总记录数
        if (typeof res.data.totaCount === 'number') {
          page.value.totaCount = res.data.totaCount;
        } else if (typeof res.data.totalCount === 'number') {
          page.value.totaCount = res.data.totalCount;
        } else if (typeof res.data.total === 'number') {
          page.value.totaCount = res.data.total;
        } else {
          page.value.totaCount = tableData.value.length;
          console.warn('没有找到总记录数，使用当前数据条数');
        }

        // 处理页数
        if (typeof res.data.pageCount === 'number') {
          page.value.pageCount = res.data.pageCount;
        } else {
          page.value.pageCount = Math.ceil(page.value.totaCount / page.value.PageSize);
        }
      } else {
        console.error('响应数据为空');
        tableData.value = [];
        page.value.totaCount = 0;
        page.value.pageCount = 0;
      }

      console.log('=== 更新后的分页信息 ===');
      console.log({
        pageData: tableData.value.length,
        pageCount: page.value.pageCount,
        totaCount: page.value.totaCount,
        PageIndex: page.value.PageIndex,
        PageSize: page.value.PageSize
      });
    })
    .catch(err => {
      console.error('=== 请求失败 ===');
      console.error('错误详情:', err);
      console.error('错误响应:', err.response);
      ElMessage.error('获取数据失败: ' + (err.response?.data?.message || err.message));
    });
};

const Dletee = (id: any) => {
  ElMessageBox.confirm(
    '确定删除该记录?',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: 'Cancel',
      type: 'warning',
    }
  )
    .then(() => {
      axios({
        url: 'http://112.126.93.146:8000/read/api/WarehouseStoking/DeleteStocking',
        method: 'post',
        data: {
          id: id
        }
      })
        .then(res => {
          if (res.data.code === 404) {
            ElMessage.info("删除的信息找不到");
            return;
          }
          if (res.data.code === 200) {
            ElMessage.success("删除成功");
            GetStockingLsit();
          }
          else {
            ElMessage.error("删除失败");
          }
        })
        .catch(err => {
          console.error('删除失败:', err);
          ElMessage.error("删除失败");
        });
    })
    .catch(() => {
      // 用户取消删除
    });
}

// 测试分页点击
const testPaginationClick = (event: any) => {
  console.log('=== 分页组件被点击 ===');
  console.log('点击事件:', event);
  console.log('当前分页状态:', page.value);
}

// 分页处理函数
const handleSizeChange = (val: number) => {
  alert('页面大小改变事件被触发！新大小：' + val);
  console.log('=== 页面大小改变 ===');
  console.log('新页面大小:', val);
  console.log('改变前状态:', page.value);

  page.value.PageSize = val;
  page.value.PageIndex = 1; // 重置到第一页

  console.log('改变后状态:', page.value);
  console.log('开始重新请求数据...');
  GetStockingLsit();
}

const handleCurrentChange = (val: number) => {
  alert('当前页改变事件被触发！新页码：' + val);
  console.log('=== 当前页改变 ===');
  console.log('新当前页:', val);
  console.log('改变前状态:', page.value);

  page.value.PageIndex = val;

  console.log('改变后状态:', page.value);
  console.log('开始重新请求数据...');
  GetStockingLsit();
}

</script>